<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能电影推荐系统 - 个人中心</title>
    <link rel="stylesheet"
          href="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/twitter-bootstrap/5.1.3/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/common.css">
    <style>
        .profile-container {
            display: flex;
            margin-top: 20px;
        }

        .profile-menu {
            width: 250px;
            margin-right: 20px;
        }

        .profile-content {
            flex: 1;
        }

        .nav-link.active {
            font-weight: bold;
            color: #0d6efd;
        }
    </style>
</head>
<body>
    <div id="toastContainer" style="position: fixed; top: 20px; right: 20px; z-index: 9999;"></div>
<nav class="navbar navbar-expand-lg navbar-dark px-3" style="background-color: #0d6efd;">
    <div class="container-fluid">
        <a class="navbar-brand" href="index.html">智能电影推荐系统</a>
        <div class="d-flex" id="userInfoArea">
            <!-- 用户信息区域将通过JavaScript动态填充 -->
        </div>
    </div>
</nav>

<div class="container profile-container">
    <div class="profile-menu">
        <div class="card">
            <div class="card-header">
                <h5>个人中心</h5>
            </div>
            <div class="list-group list-group-flush">
                <a href="#" class="list-group-item list-group-item-action active" id="profileLink">修改个人信息</a>
                <a href="#" class="list-group-item list-group-item-action" id="preferencesLink">选择偏好信息</a>
                <a href="#" class="list-group-item list-group-item-action" id="recommendationsLink">推荐的电影</a>
            </div>
        </div>
    </div>

    <div class="profile-content">
        <div id="profileContent">
            <h4>修改个人信息</h4>
            <form id="profileForm">
                <div class="mb-3">
                    <label for="nickname" class="form-label">昵称</label>
                    <input type="text" class="form-control" id="nickname" name="nickname" required>
                </div>
                <div class="mb-3">
                    <label for="password" class="form-label">新密码</label>
                    <input type="password" class="form-control" id="password" name="password"
                           placeholder="留空则不修改">
                </div>
                <button type="submit" class="btn btn-primary">保存</button>
            </form>
        </div>
        <div id="preferencesContent" style="display: none;">
            <h4>选择偏好地区</h4>
            <div id="regionButtons" class="d-flex flex-wrap gap-2 mb-4">
                <!-- 类型按钮将通过JavaScript动态填充 -->
            </div>
            <h4>选择偏好类型</h4>
            <div id="typeButtons" class="d-flex flex-wrap gap-2 mb-4">
                <!-- 类型按钮将通过JavaScript动态填充 -->
            </div>
            <button type="button" class="btn btn-primary" id="savePreferencesBtn">保存</button>
        </div>
        <div id="recommendationsContent" style="display: none;">
            <h4>推荐的电影</h4>
            <button type="button" class="btn btn-primary mb-3" id="updateRecommendationsBtn">更新推荐的电影</button>
            <div class="row" id="recommendationsList">
                <!-- 推荐电影列表将通过JavaScript动态填充 -->
            </div>
        </div>
    </div>
</div>

<script src="https://lf26-cdn-tos.bytecdntp.com/cdn/expire-1-M/twitter-bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="js/common.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        // 用户信息显示
        const userInfoArea = document.getElementById('userInfoArea');
        const user = JSON.parse(localStorage.getItem('user'));
        if (user) {
            userInfoArea.innerHTML = `
                    <span class="navbar-text me-3 text-white">欢迎您，</span>
                    <a href="profile.html" class="navbar-text text-white">${user.nickname}</a>
                    <span class="navbar-text mx-3">|</span>
                    <a href="#" class="navbar-text text-white" id="logoutBtn">退出</a>
                `;

            document.getElementById('logoutBtn').addEventListener('click', function () {
                localStorage.removeItem('user');
                window.location.href = 'index.html';
            });
        } else {
            window.location.href = 'login.html';
        }

        // 设置当前用户昵称
        if (user) {
            document.getElementById('nickname').value = user.nickname;
        }

        // 菜单切换
        document.getElementById('profileLink').addEventListener('click', function (e) {
            e.preventDefault();
            document.getElementById('profileContent').style.display = 'block';
            document.getElementById('preferencesContent').style.display = 'none';
            document.getElementById('recommendationsContent').style.display = 'none';
            document.querySelectorAll('.list-group-item').forEach(item => {
                item.classList.remove('active');
            });
            this.classList.add('active');
        });

        document.getElementById('preferencesLink').addEventListener('click', function (e) {
            e.preventDefault();
            document.getElementById('profileContent').style.display = 'none';
            document.getElementById('preferencesContent').style.display = 'block';
            document.getElementById('recommendationsContent').style.display = 'none';
            document.querySelectorAll('.list-group-item').forEach(item => {
                item.classList.remove('active');
            });
            this.classList.add('active');
        });

        document.getElementById('recommendationsLink').addEventListener('click', function (e) {
            e.preventDefault();
            document.getElementById('profileContent').style.display = 'none';
            document.getElementById('preferencesContent').style.display = 'none';
            document.getElementById('recommendationsContent').style.display = 'block';
            document.querySelectorAll('.list-group-item').forEach(item => {
                item.classList.remove('active');
            });
            this.classList.add('active');
        });

        // 更新推荐电影
        document.getElementById('updateRecommendationsBtn').addEventListener('click', function () {
            const user = JSON.parse(localStorage.getItem('user'));
            if (!user) return;

            axios.get(`${API_BASE_URL}/rec_by_region_type?region=${user.preferregion}&type=${user.prefertype}`)
                .then(response => {
                    console.log(response)
                    const recommendationsList = document.getElementById('recommendationsList');
                    recommendationsList.innerHTML = '';

                    response.data.movies.forEach(movie => {
                        const col = document.createElement('div');
                        col.className = 'col-md-3 mb-4';
                        col.innerHTML = `
                            <div class="card h-100">
                                <img src="${movie.poster}" class="card-img-top" alt="${movie.title}" style="height: 300px; object-fit: cover;" referrerpolicy="no-referrer">
                                <div class="card-body">
                                    <h5 class="card-title">${movie.title}</h5>
                                    <p class="card-text">${movie.region} · ${movie.type}</p>
                                    <a href="movie.html?id=${movie.id}" class="btn btn-primary">查看详情</a>
                                </div>
                            </div>
                        `;
                        recommendationsList.appendChild(col);
                    });
                })
                .catch(error => {
                    console.error('Error:', error);
                    showToast('获取推荐电影失败', 'danger');
                });
        });

        // 加载类型选择
        document.getElementById('preferencesLink').addEventListener('click', function () {
            axios.get(`${API_BASE_URL}/regions_types`)
                .then(response => {
                    // 填充地区按钮
                    const regionButtons = document.getElementById('regionButtons');
                    regionButtons.innerHTML = '';

                    const user = JSON.parse(localStorage.getItem('user'));
                    const selectedRegions = user?.preferregion ? user.preferregion.split(' ') : [];

                    response.data.regions.forEach(region => {
                        const button = document.createElement('button');
                        button.type = 'button';
                        button.className = `btn ${selectedRegions.includes(region) ? 'btn-primary' : 'btn-outline-primary'}`;
                        button.textContent = region;
                        button.dataset.region = region;

                        button.addEventListener('click', function () {
                            this.classList.toggle('btn-primary');
                            this.classList.toggle('btn-outline-primary');
                        });

                        regionButtons.appendChild(button);
                    });

                    // 填充类型按钮
                    const typeButtons = document.getElementById('typeButtons');
                    typeButtons.innerHTML = '';

                    const selectedTypes = user?.prefertype ? user.prefertype.split(' ') : [];

                    response.data.types.forEach(type => {
                        const button = document.createElement('button');
                        button.type = 'button';
                        button.className = `btn ${selectedTypes.includes(type) ? 'btn-primary' : 'btn-outline-primary'}`;
                        button.textContent = type;
                        button.dataset.type = type;

                        button.addEventListener('click', function () {
                            this.classList.toggle('btn-primary');
                            this.classList.toggle('btn-outline-primary');
                        });

                        typeButtons.appendChild(button);
                    });
                })
                .catch(error => console.error('Error:', error));
        });

        // 保存偏好
        document.getElementById('savePreferencesBtn').addEventListener('click', function () {
            const selectedRegions = [];
            const selectedTypes = [];
            document.querySelectorAll('#regionButtons .btn-primary').forEach(button => {
                selectedRegions.push(button.dataset.region);
            });
            document.querySelectorAll('#typeButtons .btn-primary').forEach(button => {
                selectedTypes.push(button.dataset.type);
            });

            const user = JSON.parse(localStorage.getItem('user'));
            if (!user) return;

            axios.post(`${API_BASE_URL}/profile/prefers`, {
                username: user.username,
                preferregion: selectedRegions.join(' '),
                prefertype: selectedTypes.join(' ')
            })
                .then(response => {
                    if (response.data.success) {
                        showToast('偏好保存成功');
                        user.preferregion = selectedRegions.join(' ');
                        user.prefertype = selectedTypes.join(' ');
                        localStorage.setItem('user', JSON.stringify(user));
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showToast('保存失败', 'danger');
                });
        });

        // 表单提交
        document.getElementById('profileForm').addEventListener('submit', function (e) {
            e.preventDefault();
            const nickname = document.getElementById('nickname').value;
            const password = document.getElementById('password').value;

            axios.post(`${API_BASE_URL}/profile/update`, {
                username: user.username,
                nickname: nickname,
                password: password || undefined
            })
                .then(response => {
                    if (response.data.success) {
                        showToast('修改成功');
                        user.nickname = nickname;
                        localStorage.setItem('user', JSON.stringify(user));
                        setTimeout(() => {
                            window.location.reload();
                        }, 500);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showToast('修改失败', 'danger');
                });
        });
    });
</script>
</body>
</html>